package a07_二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * a13_二叉树的所有路径复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/9
 */
public class a13_二叉树的所有路径复习2 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,
                        null,
                        new TreeNode(5)),
                new TreeNode(3));
        List<String> list = binaryTreePaths(root);
        System.out.println();
    }

    public static List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path, root);
        return result;
    }

    public static void traversal(List<String> result,
                          LinkedList<Integer> path,
                          TreeNode node){
        if(node == null){
            return;
        }
        if (node.left == null && node.right == null) {
            path.add(node.val);
            String collect = path.stream()
                    .map(i -> i.toString())
                    .collect(Collectors.joining("->"));
            result.add(collect);
            path.removeLast();
            return;
        }

        for (int i = 0; i < 2; i++) {
            path.add(node.val);
            if (i == 0) {
                traversal(result, path, node.left);
            }else {
                traversal(result, path, node.right);
            }
            path.removeLast();
        }


    }
}

